import base64
import json
import os
from json import JSONDecodeError

import faker
from locust import FastHttpUser, task, run_single_user, constant, tag

cookie = open('cookies.txt', mode='r', encoding='utf8')


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


class MemoTask(FastHttpUser):
    host = "https://www.retone-hearing.fit"
    wait_time = constant(180)
    # header = {"Content-Type": "application/json"}

    # default_headers = {"Content-Type": "application/json"}
    def on_start(self):
        self.cookie = next(cookie)

    @task
    @tag('add')
    def add_memo(self):
        " 新增 - 删除 "
        url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/addMemo'
        # print(self.header)
        data = {
            "note": str(self.header["Cookie"])+'gtevbaptwjvmq',
            "activeTime": "2023-02-28 09:03:00",
            "memoTypeEnum": "EVERY_DAY",
        }
        with self.rest('post', url, data=enconde_bs64(data), headers=self.header, name="add_del1") as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
                    if resp.json()['description'] == "用户备忘提醒数量超过最大值":
                        print('用户备忘提醒数量超过最大值')
                        resp.success()
                    else:
                        resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    # resp_data = json.loads(decode64_str(resp.js['data']))
                    # delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
                    # data = {
                    #     "memoIdList": [resp_data['memoId']]
                    # }
                    # with self.rest('post', delete_memo, data=enconde_bs64(data), headers=self.header, name="add_del2") as resp:
                        resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'data'")









if __name__ == '__main__':
    # run_single_user(MemoTask)
    os.system('locust -f locust_addmemo.py --web-host="127.0.0.1"')
    # print(fake.address())